<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8"/>
    <title>Simple example - Editor.md examples</title>
    <link rel="stylesheet" href="/layui/css/layui.css"/>
    <link rel="stylesheet" href="/model/css/style.css"/>
    <link rel="stylesheet" href="/model/css/editormd.css"/>
    <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon"/>
    <style>
        * {
            padding: 0px;
            margin: 0px;
        }
        div.CodeMirror-gutters {
            height: 100% !important;
        }
    </style>
</head>
<body>
<div id="layout">
    <div id="test-editormd">
                <textarea style="display:none;" id="mdBody">
</textarea>
    </div>
</div>
<script src="/layui/layui.js"></script>
<script src="/model/js/jquery.min.js"></script>
<script src="/model/editormd.js"></script>
<script src="/js/websocket.js"></script>
<script src="/js/UUID.js"></script>
<script src="/js/uploadImg.js" type="text/javascript"></script>
<script type="text/javascript">
    const url = "ws://localhost:8090/myWs";
    let testEditor;
    let isAutoSave = true;
    $(function () {
        //加载layui
        let layer;
        layui.use("layer",function(){
            layer = layui.layer;
        });

        let ws = websocket(url);

        ws.onerror = () => {
            setTimeout(() => {
                ws = websocket(url);
            }, 1000);
        };

        ws.onopen = (event) => {
            console.log("成功连接...");
        }

        $.get("/system/getSystemSetting", function(data){
            if (data.code == "200"){
                isAutoSave = data.data.isAutoSave;
            }
        });


        //定义上传md文件内容事件
        function uploadMd(){
            let text = $("#mdBody").text();
            //构建请求体对象
            let message = {"messageType":"SAVE_MD_BODY", "body":text, "msgId":guid()};
            //构建请求对象
            $.ajax({
                url:'/md/uploadMd',
                data:JSON.stringify(message),
                type:'post',
                dataType:'json',
                headers:{
                    Accept:"application/json",
                    "Content-Type":"application/json"
                },
                processData:false,
                cache:false
            }).done(function (data) {

            });
        }

        ws.onmessage = (event) => {
            //获取markdown的值
            let data = JSON.parse(event.data);
            if (data.messageType == "SAVE_MD_BODY"){
                uploadMd();
            }

            if (data.messageType == "GET_MD_TO_HTML"){
                //构建请求体对象
                let message = {"messageType":"SAVE_MD_HTML", "body":$("div.editormd-preview").html(), "msgId":guid()};
                $.ajax({
                    url:'/md/uploadMdToHTML',
                    data:JSON.stringify(message),
                    type:'post',
                    dataType:'json',
                    headers:{
                        Accept:"application/json",
                        "Content-Type":"application/json"
                    },
                    processData:false,
                    cache:false
                }).done(function (data) {

                });
            }

            if (data.messageType == 'SET_AUTO_SAVE_CONF'){
                if (data.body == 'true'){
                    isAutoSave = true;
                }else{
                    isAutoSave = false;
                }
            }

            if (data.messageType == "TISP_MSG"){
                // layer.msg(data.body,{"offset":'rb'});
                layer.open({
                    type:0,
                    time: 2000,
                    btn:[],
                    anim: 2,
                    closeBtn:0,
                    offset:"rb",
                    title: 'MyMarkdown提示',
                    content: data.body
                });
            }

            if (data.messageType == "CLEAR_MD_BODY"){
                testEditor.clear();
            }

            if (data.messageType == "INSERT_IMAGE"){
                testEditor.insertValue("![]("+data.body+")");
            }

            if (data.messageType == "LOAD_FILE"){
                //请求http接口获取url
                //文本内容清零
                $.get("/md/getOpenMdBody", function(data){
                    if(data.code == "200"){
                        testEditor.clear();
                        testEditor.insertValue(data.data);
                    }else{
                        layer.open({
                            type:0,
                            time: 2000,
                            btn:[],
                            anim: 2,
                            closeBtn:0,
                            offset:"rb",
                            title: 'MyMarkdown提示'
                            ,content: "加载文件内容失败!"
                        });
                    }
                });

            }

        }
        testEditor = editormd("test-editormd", {
            width: "100%",
            height: 998,
            syncScrolling: "single",
            path: "/model/lib/",
            // theme: "dark",
            // previewTheme: "dark",
            // editorTheme: "pastel-on-dark",
            markdown: "",
            codeFold: true,
            //syncScrolling : false,
            saveHTMLToTextarea: true,    // 保存 HTML 到 Textarea
            searchReplace: true,
            //watch : false,                // 关闭实时预览
            htmlDecode: "style,script,iframe|on*",            // 开启 HTML 标签解析，为了安全性，默认不开启
            //toolbar  : false,             //关闭工具栏
            //previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
            emoji: true,
            taskList: true,
            tocm: true,         // Using [TOCM]
            tex: true,                   // 开启科学公式TeX语言支持，默认关闭
            flowChart: true,             // 开启流程图支持，默认关闭
            //htmlDecode      : true,       // 开启 HTML 标签解析，为了安全性，默认不开启
            //tocContainer    : "#custom-toc-container", // 自定义 ToC 容器层
            //gfm             : false,
            //tocDropdown     : true,
            // markdownSourceCode : true, // 是否保留 Markdown 源码，即是否删除保存源码的 Textarea 标签
            sequenceDiagram : true,  // 默认不解析
            toolbarIcons : function() {
                // Or return editormd.toolbarModes[name]; // full, simple, mini
                // Using "||" set icons align right.
                return [
                    "undo", "redo", "|",
                    "bold", "del", "italic", "quote", "ucwords", "uppercase", "lowercase", "|",
                    "h1", "h2", "h3", "h4", "h5", "h6", "|",
                    "list-ul", "list-ol", "hr", "|",
                    "link", "reference-link",  "code", "preformatted-text", "code-block", "table", "datetime", "emoji", "html-entities", "pagebreak", "|",
                    "goto-line", "watch", "preview", "clear", "search"
                ]
            },
            toolbarCustomIcons   : {               // using html tag create toolbar icon, unused default <a> tag.
                lowercase        : "",
                "ucwords"        : ""
            },
            toolbarIconsClass    : {
                undo             : "fa-undo",
                redo             : "fa-repeat",
                bold             : "fa-bold",
                del              : "fa-strikethrough",
                italic           : "fa-italic",
                quote            : "fa-quote-left",
                uppercase        : "fa-font",
                h1               : "fa-header",
                h2               : "fa-header",
                h3               : "fa-header",
                h4               : "fa-header",
                h5               : "fa-header",
                h6               : "fa-header",
                "list-ul"        : "fa-list-ul",
                "list-ol"        : "fa-list-ol",
                hr               : "fa-minus",
                link             : "fa-link",
                "reference-link" : "fa-anchor",
                image            : "fa-picture-o",
                code             : "fa-code",
                "preformatted-text" : "fa-file-code-o",
                "code-block"     : "fa-file-code-o",
                table            : "fa-table",
                datetime         : "fa-clock-o",
                emoji            : "fa-smile-o",
                "html-entities"  : "fa-copyright",
                pagebreak        : "fa-newspaper-o",
                "goto-line"      : "fa-terminal", // fa-crosshairs
                watch            : "fa-eye-slash",
                unwatch          : "fa-eye",
                preview          : "fa-desktop",
                search           : "fa-search",
                fullscreen       : "fa-arrows-alt",
                clear            : "fa-eraser",
                help             : "fa-question-circle",
                info             : "fa-info-circle"
            },
            onchange : function() {
                //监听事件变化
                //构建请求体对象
                $.get("/system/setCurrentOperationFileSaveState?state=false", function(result){
                    if (isAutoSave){
                        let message = {"messageType":"SAVE_MD_BODY", "body":$("#mdBody").text(), "msgId":guid()};
                        $.ajax({
                            url:'/md/autoUploadMd',
                            data:JSON.stringify(message),
                            type:'post',
                            dataType:'json',
                            headers:{
                                Accept:"application/json",
                                "Content-Type":"application/json"
                            },
                            processData:false,
                            cache:false
                        }).done(function (data) {

                        });
                    }
                })

            },
            imageUpload : true, //必须
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "/images/upload", //必须
            onload:function (){
                initPasteDragImg(this); //必须
                // $("ul.editormd-menu i[name='h1']").text("");
                // $("ul.editormd-menu i[name='h2']").text("");
                // $("ul.editormd-menu i[name='h3']").text("");
                // $("ul.editormd-menu i[name='h4']").text("");
                // $("ul.editormd-menu i[name='h5']").text("");
                // $("ul.editormd-menu i[name='h6']").text("");
                let message = {"messageType":"LOAD_HISTORY_MD_BODY", "body":"", "msgId":guid()};
                ws.send(JSON.stringify(message));
            },
            //dialogLockScreen : false,   // 设置弹出层对话框不锁屏，全局通用，默认为true
            //dialogShowMask : false,     // 设置弹出层对话框显示透明遮罩层，全局通用，默认为true
            //dialogDraggable : false,    // 设置弹出层对话框不可拖动，全局通用，默认为true
            //dialogMaskOpacity : 0.4,    // 设置透明遮罩层的透明度，全局通用，默认值为0.1
            //dialogMaskBgColor : "#000", // 设置透明遮罩层的背景颜色，全局通用，默认为#fff
            imageUpload: true
        });

    });


</script>
</body>
</html>